package com.tcat.item.service;

import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import com.tcat.item.bo.CategoryBo;
import com.tcat.item.mapper.CategoryMapper;
import com.tcat.item.pojo.Category;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据pid查询分类
     * @param pid
     * @return
     */
    public List<Category> queryCategoryListByPid(Long pid){
        Category t=new Category();
        t.setParentId(pid);
        //select(传入一个对象)，这种查询方法是根据对象中不为空的字段查询，要根据什么字段查询就为哪个字段赋值就可以了

        List<Category> list = categoryMapper.select(t);
        //查询结果为空，应该返回404
        if(CollectionUtils.isEmpty(list)){
             throw new TcatException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return list;
    }



    /**
     * 新增分类
     * @param category
     */
    public void saveCategory(Category category) {
        //1.设置id为null
        category.setId(null);
        //2保存
        categoryMapper.insert(category);
        //3修改父节点
        Category parent=new Category();
        parent.setId(category.getParentId());
        parent.setIsParent(true);
        categoryMapper.updateByPrimaryKeySelective(parent);
    }


    /**
     * 修改分类
     * @param category
     */
    public void updateCategroy(Category category) {
        categoryMapper.updateByPrimaryKeySelective(category);
    }


    /**
     * 删除分类
     * 如果是父节点，查询所有子节点，根据子节点的id删除并维护中间表
     * @param id
     */
    public void deleteCategory(Long id) {
        Category category=categoryMapper.selectByPrimaryKey(id);
        if(category.getIsParent()){
            //1.查找所有叶子节点
            List<Category> list=new ArrayList<>();
            queryAllLeafNode(category,list);
            //2.查找所有子节点
            List<Category> list2=new ArrayList<>();
            queryAllLeafNode(category,list2);
            //3.删除tb_category中的数据 ，使用list2
            for(Category c:list2){
                categoryMapper.delete(c);
            }
            //4.维护中间表
            for(Category c:list){
                categoryMapper.deleteByCategoryIdInCategoryBrand(c.getId());
            }
        }else{
            //1.查询此节点的父亲节点的孩子个数 ==》查询还有几个兄弟
            Example example=new Example(Category.class);
            example.createCriteria().andEqualTo("parentId",category.getParentId());
            List<Category> list=categoryMapper.selectByExample(example);
            if(list.size()!=1){
                //有兄弟，直接删除自己
                categoryMapper.deleteByPrimaryKey(category.getId());
                //维护中间表
                categoryMapper.deleteByCategoryIdInCategoryBrand(category.getId());
            }else{
                //已经没有兄弟了
                categoryMapper.deleteByPrimaryKey(category.getId());
                Category parent=new Category();
                parent.setId(category.getParentId());
                parent.setIsParent(false);
                categoryMapper.updateByPrimaryKeySelective(parent);
                categoryMapper.deleteByCategoryIdInCategoryBrand(category.getId());
            }
        }
    }

    /**
     * 查询本节点下所包含的所有叶子节点 ，用于维护tb_category_brand中间表
     * @param category
     * @param leafNode
     */
    public void queryAllLeafNode(Category category, List<Category> leafNode) {
        if(!category.getIsParent()){
            leafNode.add(category);
        }
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("parentId",category.getId());
        List<Category> list=categoryMapper.selectByExample(example);
        for(Category category1:list){
            queryAllLeafNode(category1,leafNode);
        }
    }





    /**
     * 根据品牌id查询分类  用于修改品牌信息时，商品分类信息的回显
     * @param bid
     * @return
     */
    public List<Category> queryByBrandId(Long bid){
        return this.categoryMapper.queryByBrandId(bid);
    }



    public List<Category> queryByIdS(List<Long> ids){

        List<Category> list=categoryMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return list;
    }


    public List<Category> queryAllByCid3(Long id){
        Category c3=this.categoryMapper.selectByPrimaryKey(id);
        Category c2=this.categoryMapper.selectByPrimaryKey(c3.getParentId());
        Category c1=this.categoryMapper.selectByPrimaryKey(c2.getParentId());
        return Arrays.asList(c1,c2,c3);
    }



    public List<Category> queryLast() {
        List<Category> last=categoryMapper.selectList();
        return last;
    }






    public List<String> queryNamesByIds(List<Long> ids){
        List<Category> categories = categoryMapper.selectByIdList(ids);
        return categories.stream().map(category -> category.getName()).collect(Collectors.toList());
    }
}
